package com.foreknow.protals.common.util;

import com.foreknow.protals.mbg.model.UmsAdmin;
import com.foreknow.protals.mbg.model.UmsPermission;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AdminUserDetails:Spring Security所需要的用户的详情
 * 1. 用户的信息
 * 2. 权限列表
 */
public class AdminUserDetails implements UserDetails {
    private UmsAdmin umsAdmin; //用户的信息
    private List<UmsPermission> permissionList; //权限列表

    public AdminUserDetails(UmsAdmin umsAdmin,List<UmsPermission> permissionList) {
        this.umsAdmin = umsAdmin;
        this.permissionList = permissionList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //返回当前用户的权限
        //思路：
        // 1. 利用jdk8的新特性stream,可以使用filter需要过滤value不能为空
        // 2. map方法(需要转换类型List<UmsPermmission>转换为List<String>)
        return permissionList.stream()
                .filter(permission -> permission.getValue()!=null)
                .map(permission -> new SimpleGrantedAuthority(permission.getValue())).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return umsAdmin.getPassword();
    }

    @Override
    public String getUsername() {
        return umsAdmin.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 表示账号的状态（0 禁用 1 启用）
     * @return
     */
    @Override
    public boolean isEnabled() {
        return umsAdmin.getStatus().equals(1);
    }
}
